//
//  SYHomeViewController.m
//  songyao
//
//  Created by work on 16/10/18.
//  Copyright © 2016年 saikuo. All rights reserved.
//

#import "SYHomeViewController.h"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import "SYHomeTableViewCell.h"
#import "SYBannerModel.h"
#import "CustomNavController.h"
#import "SYMedicineListModel.h"
#import "SYMedicineDetailsViewController.h"
#import "SYMedicineCategoryModel.h"
#warning test
#import "SYLoginViewController.h"

@interface SYHomeViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate> {
    SDCycleScrollView *_tableHeaderView;
    NSMutableDictionary *_headerViewDictionary;
    NSInteger _requestTag;
    NSInteger _requestPid;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<SYMedicineModel> *dataArray;

@end

@implementation SYHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayBackgroundColor];
    self.navigationItem.titleView = [self navigationItemView];
    _requestTag = 0;
    _requestPid = 0;
    _headerViewDictionary = [NSMutableDictionary dictionary];
    _dataArray = [NSMutableArray<SYMedicineModel> array];
    // Do any additional setup after loading the view.
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor grayBackgroundColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(self.view);
    }];
    _tableView.tableHeaderView = [self tableHeaderView];
    WS(weakSelf);
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf requestMedicineListData];
    }];
    [self requestBannerData];
    [self requestMedicineListData];
    [self requestCategoryData];
}

- (UIView *)navigationItemView {
    UIView *view = [UIView new];
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH - 40, 25);
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    backgroundView.backgroundColor = [UIColor whiteColor];
    backgroundView.alpha = 0.6f;
    backgroundView.layer.masksToBounds = YES;
    backgroundView.layer.cornerRadius = 12;
    [view addSubview:backgroundView];
    [backgroundView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(view);
    }];
    UIImageView *imageView = [[UIImageView alloc] init];
    UIImage *image = [UIImage imageNamed:@"home_search_icon"];
    imageView.image = image;
    [view addSubview:imageView];
    [imageView makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(backgroundView.mas_centerY);
        make.left.equalTo(backgroundView.mas_left).offset(8);
        make.size.mas_equalTo(image.size);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.textColor = [UIColor grayPromptColor];
    label.font = [UIFont textFieldInputFont];
    label.text = @"搜索药品、症状、品牌";
    [view addSubview:label];
    [label makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.mas_right).offset(8);
        make.centerY.equalTo(imageView.mas_centerY);
    }];
    return view;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_tableHeaderView) {
        [_tableHeaderView adjustWhenControllerViewWillAppera];
    }
}

- (void)requestCategoryData {
    WS(weakSelf);
    [[SYHttpManager sharedHttpManager]requesGet:get_medicine_category_url parameters:nil success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        SYMedicineCategoryModel *model = [[SYMedicineCategoryModel alloc] initWithDictionary:(NSDictionary *)responseObject error:nil];
        if (model.data) {
            
        } else {
            
        }
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)requestBannerData {
    WS(weakSelf);
    [[SYHttpManager sharedHttpManager]requesGet:get_banner_url parameters:nil success:^(id responseObject) {
        SYBannerModel *model = [[SYBannerModel alloc] initWithDictionary:(NSDictionary *)responseObject error:nil];
        if (model.data && model.data.count) {
            NSMutableArray *array = [NSMutableArray array];
            [model.data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                SYBannerModelItem *item = (SYBannerModelItem *)model.data[idx];
                [array addObject:item.picUrl?item.picUrl:@""];
            }];
            weakSelf.tableHeaderView.imageURLStringsGroup = array;
        } else {
        }
    } failure:^(NSError *error) {

    }];
}

- (void)requestMedicineListData {
    WS(weakSelf);
    NSDictionary *dic = @{@"tag":@(_requestTag),@"pid":@(_requestPid)};
    NSLog(@"%@ %@",dic,get_medicine_list_url);
    [[SYHttpManager sharedHttpManager]requesGet:get_medicine_list_url parameters:dic success:^(id responseObject) {
        SYMedicineListModel *model = [[SYMedicineListModel alloc] initWithDictionary:(NSDictionary *)responseObject error:nil];
        if (model.data && model.data.count) {
            if (_requestTag == 0) {
                [_dataArray removeAllObjects];
            }
            [_dataArray addObjectsFromArray:model.data];
            _requestTag = 1;
            _requestPid = [model.pid integerValue];
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView reloadData];
        } else {
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    } failure:^(NSError *error) {
        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
}

- (SDCycleScrollView *)tableHeaderView {
    if (!_tableHeaderView) {
        NSArray *imagesURLStrings = @[
                                      @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg",
                                      @"https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg",
                                      @"http://c.hiphotos.baidu.com/image/w%3D400/sign=c2318ff84334970a4773112fa5c8d1c0/b7fd5266d0160924c1fae5ccd60735fae7cd340d.jpg"
                                      ];
        _tableHeaderView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH / 2.0f) delegate:self placeholderImage:nil];
        _tableHeaderView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        _tableHeaderView.pageDotColor = [UIColor whiteColor];
        _tableHeaderView.currentPageDotColor = [UIColor orangeNavControllerTintColor];
        _tableHeaderView.imageURLStringsGroup = imagesURLStrings;
        
    }
    return _tableHeaderView;
}


#pragma mark - tableView - dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 2) {
        return _dataArray.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0: {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"c"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"c"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                for (NSInteger i = 0; i < 8; i++) {
                    UIView *view = [[UIView alloc] init];
                    view.backgroundColor = [UIColor randomColor];
                    view.frame = CGRectMake((SCREEN_WIDTH / 4.0f) * (i % 4), (SCREEN_WIDTH / 4.0f) * (i / 4), SCREEN_WIDTH / 4.0f, SCREEN_WIDTH / 4.0f);
                    [cell.contentView addSubview:view];
                }
            }
            return cell;
        }
            break;
        case 1: {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"b"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"b"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.backgroundColor = [UIColor grayBackgroundColor];
                UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2.0f - 0.5, SCREEN_WIDTH / 4.0f - 0.5)];
                imageView1.backgroundColor = [UIColor randomColor];
                [cell.contentView addSubview:imageView1];
                
                UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, imageView1.frame.size.height + 1, imageView1.frame.size.width, imageView1.frame.size.height)];
                imageView2.backgroundColor = [UIColor randomColor];
                [cell.contentView addSubview:imageView2];
                
                UIImageView *imageView3 = [[UIImageView alloc] initWithFrame:CGRectMake(imageView1.frame.size.width + 1, 0, imageView1.frame.size.width, imageView1.frame.size.width)];
                imageView3.backgroundColor = [UIColor randomColor];
                [cell.contentView addSubview:imageView3];
            }
            return cell;
        }
            break;
        case 2: {
            SYHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"d"];
            if (!cell) {
                cell = [[SYHomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"d"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.data = _dataArray[indexPath.row];
            return cell;
        }
            break;
    }
    return [UITableViewCell new];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

#pragma mark - tableView - delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        case 1: {
            return SCREEN_WIDTH / 2.0f;
        }
            break;
    }
    return 105;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 0.0f;
            break;
            
        default:
            break;
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view;
    NSString *key = [NSString stringWithFormat:@"%ld",(long)section];
    if (_headerViewDictionary[key]) {
        view = (UIView *)_headerViewDictionary[key];
    } else {
        view = [self sectionHeader:section];
        [_headerViewDictionary setObject:view forKey:[NSString stringWithFormat:@"%ld",(long)section]];
    }
    return view;
}

- (UIView *)sectionHeader:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont titleFont];
    label.backgroundColor = [UIColor whiteColor];
    label.textColor = [UIColor orangeNavControllerTintColor];
    switch (section) {
        case 1: {
            label.text = @"主题特卖";
            [view addSubview:label];
        }
            break;
        case 2: {
            label.text = @"热卖商品";
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectZero];
            lineView.backgroundColor = [UIColor cuttingLineColor];
            
            [view addSubview:label];
            [view addSubview:lineView];
            [lineView makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(label);
                make.height.equalTo(@(0.5));
                make.bottom.equalTo(label.mas_bottom).offset(-2.5);
            }];
        }
            break;
        default:
            break;
    }
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        SYMedicineDetailsViewController *vc = [[SYMedicineDetailsViewController alloc] init];
        vc.model = _dataArray[indexPath.row];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    SYLoginViewController *vc = [[SYLoginViewController alloc] init];
    CustomNavController *nav = [[CustomNavController alloc] initWithRootViewController:vc];
    [nav customSetting];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
